package main

import (
	"encoding/json"
	"fmt"
	"os"

	"github.com/gogo/protobuf/proto"
	tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
	"github.com/tendermint/tendermint/types"
)

func main() {
	txs := Read(4, "i1")
	for _, txpb := range txs {
		tx := new(tmproto.Tx)
		if err := proto.Unmarshal(txpb, tx); err != nil {
			fmt.Println("Error unmarshaling tx:", err)
			continue
		}
		fmt.Println(tx.OperationType)
		data := new(tmproto.FileData)
		if err := proto.Unmarshal(tx.Data, data); err != nil {
			panic(err)
		}
		fmt.Println(data.ObjectId)
	}

}

func Read(height int64, chain_id string) types.Txs {
	filepath := "/home/llm/tdmt12/full/tendermint_subject2/my_app/blockdata"
	fileName := fmt.Sprintf("%s/block_%d_%s.dat", filepath, height, chain_id)

	file, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0777)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	// reader := bufio.NewReader(file)

	var txs types.Txs
	// 读取文件内容
	jsonData, err := os.ReadFile(fileName)
	if err != nil {
		return nil
	}

	// 将 JSON 数据转换为结构体
	err = json.Unmarshal(jsonData, &txs)
	if err != nil {
		return nil
	}
	// for {
	// 	line, _, err := reader.ReadLine()
	// 	if err != nil {
	// 		if errors.Is(err, io.EOF) {
	// 			break
	// 		} else {
	// 			panic(err)
	// 		}
	// 	}
	// 	txs = append(txs, line)
	// }
	return txs
}
